//
//  CZTabBar.m
//  A01-CZ彩票
//
//  Created by apple on 15-6-13.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZTabBar.h"
#import "UIView+Ex.h"
#import "CZTabBarButton.h"
@interface CZTabBar ()
//记录上一次点击的按钮
@property (nonatomic, weak) UIButton *preButton;
@end

@implementation CZTabBar

//添加一个tabBarItem。对应tabBarController中的一个子控制器
- (void)addTabBarItem:(NSString *)name{
    CZTabBarButton *btn = [CZTabBarButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:btn];  //self.subviews
    /**
     *  记录当前按钮的索引
     */
    btn.tag = self.subviews.count - 1;
    //拼图片的名称
    NSString *imgName = [NSString stringWithFormat:@"TabBar_%@_new",name];
    NSString *selImgName = [NSString stringWithFormat:@"TabBar_%@_selected_new",name];
    //设置按钮上显示的图片
    [btn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selImgName] forState:UIControlStateSelected];
   

    //让按钮的大小和图片的大小一致
    [btn sizeToFit];
    
    //点击按钮。设置选中状态
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    
    //让第一个按钮默认选中
    if (self.subviews.count == 1) {
        [self btnClick:btn];
    }
    
    
    
//    [btn setHighlighted:NO];
    
    
}
- (void)btnClick:(UIButton *)sender{
    //把上一个按钮的选中状态去掉
    self.preButton.selected = NO;
    //设置当前点击的按钮选中
    sender.selected = YES;
    
    //记录上一个按钮
    self.preButton = sender;
    
    //3 合适的时机，向代理对象发送消息
    if([self.delegate respondsToSelector:@selector(tabBar:didClickedButton:)]){
        // 当前点击的按钮的索引
        [self.delegate tabBar:self didClickedButton:sender.tag];
    }
}

//调整每一个tabBarItem的位置
- (void)layoutSubviews{
    [super layoutSubviews];
    
    //遍历5个tabBarItem
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *btn = self.subviews[i];
        //使用控件的x  width属性的时候。先要导入UIview分类
        btn.x = i * btn.width;

    }
    
}

@end
